package com.csaba.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * @author gyenes
 */
public class OneLineFormatter extends Formatter
{
	private final SimpleDateFormat sdfTimestamp = new SimpleDateFormat("yyyyMMdd HHmmss");

	@Override
	public String format( final LogRecord record )
	{
		// seq level date time message
		final StringBuilder sb = new StringBuilder();
		sb.append(padding(String.valueOf(record.getSequenceNumber()), 6, false)).append(" ");
		final long millis = record.getMillis();
		sb.append(sdfTimestamp.format(new Date(millis))).append(" ");
		sb.append(padding(record.getLevel().toString(), 8, true)).append(" ");
		sb.append(record.getMessage());

		final Throwable tr = record.getThrown();
		if ( tr != null )
		{
			try
			{
				final ByteArrayOutputStream baos = new ByteArrayOutputStream();
				tr.printStackTrace(new PrintStream(baos));
				baos.flush();
				baos.close();

				final String stackTrace = new String(baos.toByteArray());
				sb.append("\n").append(stackTrace);
			}
			catch ( final IOException e )
			{
				sb.append("\n ERROR: failed to generate stack trace for exception: " + e);
			}
		}

		return sb.append("\n").toString();
	}

	private static final String PADDING_HELPER = "                                                                      ";

	private String padding( final String what, final int size, final boolean left )
	{
		String result = null;
		if ( left )
		{
			result = what;
			if ( what.length() < size )
			{
				result += PADDING_HELPER.substring(0, size - what.length());
			}
		}
		else
		{
			if ( what.length() < size )
			{
				result = PADDING_HELPER.substring(0, size - what.length());
			}
			if ( result != null )
			{
				result += what;
			}
			else
			{
				result = what;
			}
		}
		return result;
	}

}
